package com.woniu.utils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.io.FileInputStream;

/**
 * 生成Excel文件的工具类
 */
public class ExcelUtil {

    public static HSSFWorkbook getHSSFWorkbook(String sheetName,String[] title,String[][] values,HSSFWorkbook wb){
        if (wb == null){
            wb = new HSSFWorkbook();
        }
        HSSFSheet sheet = wb.createSheet(sheetName);
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        HSSFCell cell = null;
        for (int i = 0;i < title.length;i++){
            cell = row.createCell(i);
            cell.setCellValue(title[i]);
            cell.setCellStyle(style);
        }

        for (int i = 0;i < values.length;i++){
            row = sheet.createRow(i + 1);
            for (int j = 0;j < values[i].length;j++){
                row.createCell(j).setCellValue(values[i][j]);
            }
        }

        return wb;
    }

    public void sheet1(){
        String filePath = "C:\\Users\\lx\\Desktop\\graduate.xls";
        FileInputStream stream;
        try {
            stream = new FileInputStream(filePath);
            HSSFWorkbook workbook = new HSSFWorkbook(stream);// 读取现有的Excel
            HSSFSheet sheet = workbook.getSheet("Sheet1");// 得到指定名称的Sheet
            for (Row row : sheet) {
                for (Cell cell : row) {
                    System.out.print(cell + "\t");
                }
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ExcelUtil excelUtil = new ExcelUtil();
        try {
            excelUtil.sheet1();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}




























